package service

import (
	"context"
	openapi "github.com/alibabacloud-go/darabonba-openapi/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v2/client"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gcfg"
	"github.com/gogf/gf/v2/util/grand"
	"lot_admin_api/api"
	"lot_admin_api/internal/consts"
	"lot_admin_api/internal/model"
	"lot_admin_api/utility/response"
	"strconv"
)

type sPhoneCode struct{}

var (
	insPhoneCode = sPhoneCode{}
)

func PhoneCode() *sPhoneCode {
	return &insPhoneCode
}

// GetPhoneCode 获取手机验证码
func (s *sPhoneCode) GetPhoneCode(ctx context.Context, info *api.AliyunShortMessageReq) (*model.AliyunShortMessageRes, error) {
	r := g.RequestFromCtx(ctx)      // 获取请求对象
	code := grand.N(100000, 999999) // 生成随机的六位数验证码
	phoneCode := strconv.Itoa(code)
	SMS, _ := g.Cfg().Get(ctx, "custom.sms") // 将int32转换字符串
	SMSPhone := SMS.String() + info.Phone    // 短信存在redis的key
	redisDB, _ := g.Redis("cache").Conn(ctx) // 获取redis实体
	var err error
	//v, _ := conn.Do(ctx, "GET", SMSPhone)

	// 当库里没有数据时， 发送验证码
	client, _ := PhoneCode().CreatePhoneCodeClient(ctx)

	SignName, _ := gcfg.Instance().Get(ctx, "aliyun.SignName")         // 从配置中获取签名
	TemplateCode, _ := gcfg.Instance().Get(ctx, "aliyun.TemplateCode") // 从配置中获取code
	// 配置发送短信的模板
	sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
		SignName:      tea.String(SignName.String()),
		TemplateCode:  tea.String(TemplateCode.String()),
		PhoneNumbers:  tea.String(info.Phone),
		TemplateParam: tea.String(`{"code":` + phoneCode + `}`), //
	}
	// 复制代码运行请自行打印 API 的返回值
	if 0 == 1 {
		_, err = client.SendSms(sendSmsRequest)
	}
	// 发送短信错误
	if err != nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), err.Error())
	}
	// 发送短信成功后保存验证码到redis  保存时间为5分钟 300
	if _, err := redisDB.Do(ctx, "SET", SMSPhone, code, "EX", 300); err != nil {
		return nil, err
	}
	return &model.AliyunShortMessageRes{
		Phone: info.Phone,
		Code:  phoneCode,
	}, err
}

// CreatePhoneCodeClient 配置短信发送的信息
func (s *sPhoneCode) CreatePhoneCodeClient(ctx context.Context) (_result *dysmsapi20170525.Client, _err error) {
	accessKeyId, _ := gcfg.Instance().Get(ctx, "aliyun.AccessKeyId")         // 从系统中获取配置accessKeyId
	accessKeySecret, _ := gcfg.Instance().Get(ctx, "aliyun.AccessKeySecret") // 从系统中获取配置accessKeySecret
	config := &openapi.Config{
		// 您的AccessKey ID
		AccessKeyId: tea.String(accessKeyId.String()),
		// 您的AccessKey Secret
		AccessKeySecret: tea.String(accessKeySecret.String()),
	}
	// 访问的域名
	config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
	_result = &dysmsapi20170525.Client{}
	_result, _err = dysmsapi20170525.NewClient(config)
	return _result, _err
}

// IsSMSSuccess 校验短信验证码是否正确
func (s *sPhoneCode) IsSMSSuccess(ctx context.Context, req *model.IsSMSSuccess) {
	r := g.RequestFromCtx(ctx)
	redisDB, _ := g.Redis("cache").Conn(ctx) // 获取redis实体
	SMS, _ := g.Cfg().Get(ctx, "custom.sms") // 将获取手机验证码存在redis的key
	SMSPhone := SMS.String() + req.Phone     // 短信存在redis的key
	// 校验短信验证码是否正确
	if findSMS, _ := redisDB.Do(ctx, "GET", SMSPhone); findSMS.Val() != req.PhoneCode {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), "验证码不正确")
	}
}
